import argparse
import boto3

def set_folder_permissions(bucket_name, aws_access_key_id, aws_secret_access_key):
    # 创建S3客户端
    s3_client = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)

    # 获取S3桶中所有对象
    response = s3_client.list_objects_v2(Bucket=bucket_name)

    # 遍历桶中的所有对象
    for obj in response.get('Contents', []):
        # 获取对象键
        object_key = obj['Key']

        # 判断是否为文件夹
        if object_key.endswith('/'):
            # 获取对象的ACL
            response = s3_client.get_object_acl(Bucket=bucket_name, Key=object_key)

            # 打印当前对象的权限设置
            print(f"对象 {object_key} 的当前权限设置为：")
            for grant in response['Grants']:
                grantee = grant['Grantee']
                permission = grant['Permission']
                if grantee.get('Type') == 'Group' and grantee.get('URI') == 'http://acs.amazonaws.com/groups/global/AllUsers':
                    grantee_name = '公共用户'
                else:
                    grantee_name = grantee.get('DisplayName') or grantee.get('ID')
                print(f"{grantee_name} : {permission}")

            # 修改对象权限为公共可读
            s3_client.put_object_acl(Bucket=bucket_name, Key=object_key, ACL='public-read')

            # 获取修改后的ACL
            response = s3_client.get_object_acl(Bucket=bucket_name, Key=object_key)

            # 打印修改后的权限设置
            print(f"对象 {object_key} 的修改后权限设置为：")
            for grant in response['Grants']:
                grantee = grant['Grantee']
                permission = grant['Permission']
                if grantee.get('Type') == 'Group' and grantee.get('URI') == 'http://acs.amazonaws.com/groups/global/AllUsers':
                    grantee_name = '公共用户'
                else:
                    grantee_name = grantee.get('DisplayName') or grantee.get('ID')
                print(f"{grantee_name} : {permission}")
            print("--------------------")

if __name__ == '__main__':
    # 创建解析器
    parser = argparse.ArgumentParser(description="上传文件到 S3")
    parser.add_argument("--key", required=True, help="AWS Access Key ID")
    parser.add_argument("--secret", required=True, help="AWS Secret Access Key")
    parser.add_argument("--bucket", required=True, help="S3 Bucket 名称")

    # 解析命令行参数
    args = parser.parse_args()

    # 设置文件夹权限并打印结果
    set_folder_permissions(args.bucket, args.key, args.secret)
